<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择出库类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_outbound_order_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择出库状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_outbound_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:outbound:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:outbound:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:outbound:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:outbound:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outboundOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单号" align="center" prop="orderNo" />
      <el-table-column label="出库类型" align="center" prop="orderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_outbound_order_type" :value="scope.row.orderType"/>
        </template>
      </el-table-column>
      <el-table-column label="出库状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_outbound_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="货主" align="center" prop="ownerName" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="客户" align="center" prop="customerName" />
      <el-table-column label="预期出库日期" align="center" prop="expectedDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['wms:outbound:order:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:outbound:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:outbound:order:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="handlePrintPickingList(scope.row)"
            v-hasPermi="['wms:outbound:order:query']"
            v-if="scope.row.orderStatus === 'ALLOCATED' || scope.row.orderStatus === 'PARTIAL_ALLOCATED' || scope.row.orderStatus === 'PICKING' || scope.row.orderStatus === 'PICKED'"
          >打印拣货单</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['wms:outbound:order:allocate', 'wms:outbound:order:pick', 'wms:outbound:order:ship', 'wms:outbound:order:cancel']">
            <el-button size="mini" type="text">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                command="allocate" 
                icon="el-icon-s-grid" 
                v-hasPermi="['wms:outbound:order:allocate']"
                v-if="scope.row.orderStatus === 'PENDING' || scope.row.orderStatus === 'PARTIAL_ALLOCATED' || scope.row.orderStatus === 'ALLOCATION_FAILED'"
              >库存分配</el-dropdown-item>
              <el-dropdown-item 
                command="startPick" 
                icon="el-icon-s-operation" 
                v-hasPermi="['wms:outbound:order:pick']"
                v-if="scope.row.orderStatus === 'ALLOCATED' || scope.row.orderStatus === 'PARTIAL_ALLOCATED'"
              >开始拣货</el-dropdown-item>
              <el-dropdown-item 
                command="pick" 
                icon="el-icon-s-check" 
                v-hasPermi="['wms:outbound:order:pick']"
                v-if="scope.row.orderStatus === 'PICKING'"
              >确认拣货</el-dropdown-item>
              <el-dropdown-item 
                command="ship" 
                icon="el-icon-truck" 
                v-hasPermi="['wms:outbound:order:ship']"
                v-if="scope.row.orderStatus === 'PICKED'"
              >确认出库</el-dropdown-item>
              <el-dropdown-item 
                command="cancel" 
                icon="el-icon-close" 
                v-hasPermi="['wms:outbound:order:cancel']"
                v-if="scope.row.orderStatus !== 'SHIPPED' && scope.row.orderStatus !== 'CANCELLED'"
              >取消出库</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="货主" prop="ownerId">
              <el-select v-model="form.ownerId" placeholder="请选择货主" @change="handleOwnerChange">
                <el-option
                  v-for="item in ownerOptions"
                  :key="item.id"
                  :label="item.ownerName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.id"
                  :label="item.warehouseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入出库单号" :disabled="form.orderId != null">
                <el-button slot="append" icon="el-icon-refresh" @click="generateOrderNo" v-if="form.orderId == null" :disabled="!form.ownerId">生成</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="出库类型" prop="orderType">
              <el-select v-model="form.orderType" placeholder="请选择出库类型">
                <el-option
                  v-for="dict in dict.type.wms_outbound_order_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户">
                <el-option
                  v-for="item in customerOptions"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预期出库日期" prop="expectedDate">
              <el-date-picker clearable
                v-model="form.expectedDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择预期出库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 出库明细 -->
        <el-divider content-position="left">出库明细</el-divider>
        <div class="mb8">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetail">添加明细</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDetail" :disabled="!selectedDetailIds.length">删除明细</el-button>
        </div>
        
        <el-table :data="form.detailList" @selection-change="handleDetailSelectionChange" border>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="商品编码" prop="itemCode" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemCode" placeholder="请输入商品编码" size="mini" @blur="handleItemCodeBlur(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="itemName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" placeholder="请输入商品名称" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="需求数量" prop="requiredQty" width="140">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.requiredQty" :min="0" :precision="2" size="mini" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="已分配数量" prop="allocatedQty" width="100" v-if="form.orderId != null">
            <template slot-scope="scope">
              <span>{{ scope.row.allocatedQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已拣货数量" prop="pickedQty" width="100" v-if="form.orderId != null">
            <template slot-scope="scope">
              <span>{{ scope.row.pickedQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已出库数量" prop="shippedQty" width="100" v-if="form.orderId != null">
            <template slot-scope="scope">
              <span>{{ scope.row.shippedQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="单位" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="明细状态" prop="detailStatus" width="100" v-if="form.orderId != null">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_outbound_detail_status" :value="scope.row.detailStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleRemoveDetail(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 出库单详情对话框 -->
    <el-dialog title="出库单详情" :visible.sync="detailOpen" width="1200px" append-to-body>
      <el-form :model="detailForm" label-width="100px" class="demo-form-inline">
        <el-row>
          <el-col :span="8">
            <el-form-item label="出库单号">
              <span>{{ detailForm.orderNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货主名称">
              <span>{{ detailForm.ownerName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称">
              <span>{{ detailForm.warehouseName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <span>{{ detailForm.customerName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预期出库日期">
              <span>{{ detailForm.expectedDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库状态">
              <dict-tag :options="dict.type.wms_outbound_order_status" :value="detailForm.orderStatus"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="创建时间">
              <span>{{ parseTime(detailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人">
              <span>{{ detailForm.createBy }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际出库日期" v-if="detailForm.actualDate">
              <span>{{ detailForm.actualDate }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <span>{{ detailForm.remark }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <el-divider content-position="left">出库明细</el-divider>
      <el-table :data="detailForm.detailList" border>
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="商品编码" prop="itemCode" width="120" />
        <el-table-column label="商品名称" prop="itemName" width="150" />
        <el-table-column label="需求数量" prop="requiredQty" width="100" />
        <el-table-column label="已分配数量" prop="allocatedQty" width="100" />
        <el-table-column label="已拣货数量" prop="pickedQty" width="100" />
        <el-table-column label="已出库数量" prop="shippedQty" width="100" />
        <el-table-column label="单位" prop="unit" width="80" />
        <el-table-column label="明细状态" prop="detailStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.wms_outbound_detail_status" :value="scope.row.detailStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作" align="center" width="200" v-if="detailForm.orderStatus === 'PENDING'">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-grid"
              @click="handleDetailAllocate(scope.row)"
              v-hasPermi="['wms:outbound:order:allocate']"
            >库存分配</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" v-else-if="detailForm.orderStatus === 'PICKING'">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-check"
              @click="handleDetailPick(scope.row)"
              v-hasPermi="['wms:outbound:order:pick']"
            >确认拣货</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" v-else-if="detailForm.orderStatus === 'PICKED'">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-truck"
              @click="handleDetailShip(scope.row)"
              v-hasPermi="['wms:outbound:order:ship']"
            >确认出库</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePrintPickingList(detailForm)" v-if="detailForm.orderStatus === 'ALLOCATED' || detailForm.orderStatus === 'PICKED' || detailForm.orderStatus === 'SHIPPED'">打印拣货单</el-button>
        <el-button @click="detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 拣货单打印对话框 -->
    <el-dialog title="拣货单" :visible.sync="printOpen" width="800px" append-to-body>
      <div id="pickingListContent" class="picking-list">
        <div class="picking-header">
          <h2 style="text-align: center; margin: 0 0 20px 0;">拣货单</h2>
          <div class="header-info">
            <div class="info-row">
              <span><strong>出库单号：</strong>{{ printForm.orderNo }}</span>
              <span style="margin-left: 50px;"><strong>打印时间：</strong>{{ currentTime }}</span>
            </div>
            <div class="info-row" style="margin-top: 10px;">
              <span><strong>货主：</strong>{{ printForm.ownerName }}</span>
              <span style="margin-left: 50px;"><strong>仓库：</strong>{{ printForm.warehouseName }}</span>
            </div>
            <div class="info-row" style="margin-top: 10px;">
              <span><strong>客户：</strong>{{ printForm.customerName }}</span>
              <span style="margin-left: 50px;"><strong>预期出库日期：</strong>{{ printForm.expectedDate }}</span>
            </div>
          </div>
        </div>
        
        <el-table :data="printForm.allocationList" border style="margin-top: 20px;">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="商品编码" prop="itemCode" width="120" />
          <el-table-column label="商品名称" prop="itemName" width="150" />
          <el-table-column label="库位" prop="locationCode" width="100" />
          <el-table-column label="批次号" prop="batchNo" width="120" />
          <el-table-column label="分配数量" prop="allocatedQty" width="100" align="center" />
          <el-table-column label="单位" prop="unit" width="80" align="center" />
          <el-table-column label="生产日期" prop="productionDate" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.productionDate || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="过期日期" prop="expirationDate" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.expirationDate || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分配状态" width="100" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_inventory_allocation_status" :value="scope.row.allocationStatus"/>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="picking-footer" style="margin-top: 30px;">
          <div class="footer-info">
            <div class="info-row">
              <span><strong>拣货员：</strong>_________________</span>
              <span style="margin-left: 100px;"><strong>拣货时间：</strong>_________________</span>
            </div>
            <div class="info-row" style="margin-top: 20px;">
              <span><strong>复核员：</strong>_________________</span>
              <span style="margin-left: 100px;"><strong>复核时间：</strong>_________________</span>
            </div>
          </div>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePrint">打印</el-button>
        <el-button @click="printOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutboundOrder, getOutboundOrder, delOutboundOrder, addOutboundOrder, updateOutboundOrder, allocateInventory, startPicking, confirmPicking, confirmOutbound, cancelOutboundOrder, generateOutboundOrderNo } from "@/api/wms/outboundOrder";
import { listCargoOwner } from "@/api/wms/cargoOwner";
import { listWarehouse } from "@/api/wms/warehouse";
import { listCustomer } from "@/api/wms/customer";
import { getItemByCode } from "@/api/wms/item";
import { generateOrderNumber } from "@/api/wms/orderNumberRule";
import { getInventoryAllocationByOrderId } from "@/api/wms/inventoryAllocation";

export default {
  name: "OutboundOrder",
  dicts: ['wms_outbound_order_type', 'wms_outbound_order_status', 'wms_outbound_detail_status', 'wms_inventory_allocation_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单表格数据
      outboundOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示打印对话框
      printOpen: false,
      // 是否显示详情对话框
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        orderType: null,
        orderStatus: null,
      },
      // 表单参数
      form: {
        orderId: null,
        orderNo: null,
        orderType: null,
        ownerId: null,
        warehouseId: null,
        customerId: null,
        expectedDate: null,
        remark: null,
        detailList: []
      },
      // 表单校验
      rules: {
        orderType: [
          { required: true, message: "出库类型不能为空", trigger: "change" }
        ],
        ownerId: [
          { required: true, message: "货主不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ]
      },
      // 选项数据
      ownerOptions: [],
      warehouseOptions: [],
      customerOptions: [],
      // 选中的明细ID
      selectedDetailIds: [],
      // 打印表单
      printForm: {
        orderNo: '',
        ownerName: '',
        warehouseName: '',
        customerName: '',
        expectedDate: '',
        allocationList: []
      },
      // 详情表单
      detailForm: {
        orderId: null,
        orderNo: '',
        orderType: '',
        ownerId: null,
        ownerName: '',
        warehouseId: null,
        warehouseName: '',
        customerId: null,
        customerName: '',
        expectedDate: '',
        actualDate: '',
        orderStatus: '',
        remark: '',
        createBy: '',
        createTime: '',
        detailList: []
      },
      // 当前时间
      currentTime: ''
    };
  },
  created() {
    this.getList();
    this.loadOwnerOptions();
    this.loadWarehouseOptions();
    this.loadCustomerOptions();
  },
  methods: {
    /** 查询出库单列表 */
    getList() {
      this.loading = true;
      listOutboundOrder(this.queryParams).then(response => {
        this.outboundOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNo: null,
        orderType: null,
        ownerId: null,
        warehouseId: null,
        customerId: null,
        expectedDate: null,
        remark: null,
        detailList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出库单";
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const orderId = row.orderId;
      getOutboundOrder(orderId).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 详情中明细行库存分配 */
    handleDetailAllocate(row) {
      const orderId = this.detailForm.orderId;
      allocateInventory(orderId).then(response => {
        this.$modal.msgSuccess("库存分配成功");
        this.getList();
        // 刷新详情数据
        getOutboundOrder(orderId).then(response => {
          this.detailForm = response.data;
        });
      });
    },
    /** 详情中明细行确认拣货 */
    handleDetailPick(row) {
      const orderId = this.detailForm.orderId;
      confirmPicking(orderId).then(response => {
        this.$modal.msgSuccess("拣货确认成功");
        this.getList();
        // 刷新详情数据
        getOutboundOrder(orderId).then(response => {
          this.detailForm = response.data;
        });
      });
    },
    /** 详情中明细行确认出库 */
    handleDetailShip(row) {
      const orderId = this.detailForm.orderId;
      confirmOutbound(orderId).then(response => {
        this.$modal.msgSuccess("出库确认成功");
        this.getList();
        // 刷新详情数据
        getOutboundOrder(orderId).then(response => {
          this.detailForm = response.data;
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOutboundOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改出库单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 校验明细数据
          if (this.form.detailList.length === 0) {
            this.$modal.msgError("请至少添加一条出库明细");
            return;
          }
          
          // 校验明细中的需求数量
          for (let i = 0; i < this.form.detailList.length; i++) {
            const detail = this.form.detailList[i];
            if (!detail.requiredQty || detail.requiredQty <= 0) {
              this.$modal.msgError(`第${i + 1}行明细的需求数量必须大于0`);
              return;
            }
            if (!detail.itemCode || detail.itemCode.trim() === '') {
              this.$modal.msgError(`第${i + 1}行明细的商品编码不能为空`);
              return;
            }
          }
          
          if (this.form.orderId != null) {
            updateOutboundOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutboundOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除出库单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOutboundOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/outboundOrder/export', {
        ...this.queryParams
      }, `outboundOrder_${new Date().getTime()}.xlsx`)
    },
    /** 更多操作 */
    handleCommand(command, row) {
      switch (command) {
        case "allocate":
          this.handleAllocate(row);
          break;
        case "startPick":
          this.handleStartPick(row);
          break;
        case "pick":
          this.handlePick(row);
          break;
        case "ship":
          this.handleShip(row);
          break;
        case "cancel":
          this.handleCancel(row);
          break;
      }
    },
    /** 库存分配 */
    handleAllocate(row) {
      this.$modal.confirm('是否确认对出库单"' + row.orderNo + '"进行库存分配？').then(function() {
        return allocateInventory(row.orderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("库存分配成功");
      }).catch(() => {});
    },
    /** 开始拣货 */
    handleStartPick(row) {
      this.$modal.confirm('是否确认对出库单"' + row.orderNo + '"开始拣货？').then(function() {
        return startPicking(row.orderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("开始拣货成功");
      }).catch(() => {});
    },
    /** 确认拣货 */
    handlePick(row) {
      this.$modal.confirm('是否确认对出库单"' + row.orderNo + '"进行拣货确认？').then(function() {
        return confirmPicking(row.orderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("拣货确认成功");
      }).catch(() => {});
    },
    /** 确认出库 */
    handleShip(row) {
      this.$modal.confirm('是否确认对出库单"' + row.orderNo + '"进行出库确认？').then(function() {
        return confirmOutbound(row.orderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("出库确认成功");
      }).catch(() => {});
    },
    /** 取消出库 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消出库单"' + row.orderNo + '"？').then(function() {
        return cancelOutboundOrder(row.orderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 加载货主选项 */
    loadOwnerOptions() {
      listCargoOwner({ status: '0' }).then(response => {
        this.ownerOptions = response.rows;
      });
    },
    /** 加载仓库选项 */
    loadWarehouseOptions() {
      listWarehouse({ status: '0' }).then(response => {
        this.warehouseOptions = response.rows;
      });
    },
    /** 加载客户选项 */
    loadCustomerOptions() {
      listCustomer({ status: '0' }).then(response => {
        this.customerOptions = response.rows;
      });
    },
    /** 货主变更处理 */
    handleOwnerChange() {
      // 货主变更时清空出库单号
      this.form.orderNo = null;
    },
    /** 生成出库单号 */
    generateOrderNo() {
      if (!this.form.ownerId) {
        this.$modal.msgError("请先选择货主");
        return;
      }
      generateOrderNumber(this.form.ownerId, 'OUTBOUND').then(response => {
        this.form.orderNo = response.data;
      }).catch(() => {
        this.$modal.msgError("生成出库单号失败");
      });
    },
    /** 添加明细 */
    handleAddDetail() {
      const newDetail = {
        itemCode: '',
        itemName: '',
        requiredQty: 0,
        unit: '',
        remark: ''
      };
      this.form.detailList.push(newDetail);
    },
    /** 删除明细 */
    handleDeleteDetail() {
      if (this.selectedDetailIds.length === 0) {
        this.$modal.msgError("请选择要删除的明细");
        return;
      }
      this.form.detailList = this.form.detailList.filter((item, index) => !this.selectedDetailIds.includes(index));
      this.selectedDetailIds = [];
    },
    /** 移除单个明细 */
    handleRemoveDetail(index) {
      this.form.detailList.splice(index, 1);
    },
    /** 明细选择变化 */
    handleDetailSelectionChange(selection) {
      this.selectedDetailIds = selection.map((item, index) => {
        return this.form.detailList.findIndex(detail => detail === item);
      });
    },
    /** 商品编码失焦处理 */
     async handleItemCodeBlur(row) {
       if (row.itemCode && row.itemCode.trim() !== '') {
         try {
           const response = await getItemByCode(row.itemCode.trim());
           if (response.code === 200 && response.data) {
             row.itemId = response.data.id;
             row.itemName = response.data.itemName;
             row.unit = response.data.unit || row.unit;
           } else {
             this.$modal.msgError(`没有找到商品编码为 ${row.itemCode} 的商品`);
             row.itemName = '';
             row.itemId = null;
           }
         } catch (error) {
           console.error('查询商品信息失败:', error);
           this.$modal.msgError(`查询商品编码 ${row.itemCode} 失败`);
         }
        }
      },
      /** 打印拣货单 */
      handlePrintPickingList(row) {
        // 获取库存分配信息
        this.loadAllocationData(row.orderId).then(() => {
          this.printForm.orderNo = row.orderNo;
          this.printForm.ownerName = row.ownerName;
          this.printForm.warehouseName = row.warehouseName;
          this.printForm.customerName = row.customerName;
          this.printForm.expectedDate = row.expectedDate;
          this.currentTime = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
          this.printOpen = true;
        });
      },
      /** 加载分配数据 */
      async loadAllocationData(orderId) {
        try {
          const response = await getInventoryAllocationByOrderId(orderId);
          if (response.code === 200) {
            this.printForm.allocationList = response.data;
          } else {
            this.$modal.msgError('获取分配数据失败');
          }
        } catch (error) {
          console.error('加载分配数据失败:', error);
          this.$modal.msgError('加载分配数据失败');
        }
      },
      /** 打印 */
      handlePrint() {
        const printContent = document.getElementById('pickingListContent');
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
          <html>
            <head>
              <title>拣货单</title>
              <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .picking-list { width: 100%; }
                .picking-header { margin-bottom: 20px; }
                .info-row { margin: 5px 0; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; }
                .picking-footer { margin-top: 30px; }
                @media print {
                  body { margin: 0; }
                  .no-print { display: none; }
                }
              </style>
            </head>
            <body>
              ${printContent.innerHTML}
            </body>
          </html>
        `);
        printWindow.document.close();
        printWindow.print();
        printWindow.close();
      }
    }
  };
</script>